<!-- 新的文章统计主页面 -->
<template>
  <div>
    <!-- 查询条件表单组件 -->
    <div class="bg-white h-auto my-2 mb-2 py-2">
      <BasicForm @register="registerForm" @submit="handleSubmit" />
    </div>
    <div class="flex">
      <!-- 按发布人统计文章table组件 -->
      <div class="flex flex-col pr-4 w-2/4">
        <BasicTable
          @register="registerInUserTable"
          :can-resize="true"
          :bordered="true"
          :striped="true"
          :loading="false"
          :data-source="authorsData.authors"
        >
          <template #toolbar>
            <a-button @click="exportInUserToExcel"> 导出Excel </a-button>
          </template>
        </BasicTable>
      </div>

      <!-- 按发布部门统计文章table组件 -->
      <div class="flex flex-col pr-4 w-2/4">
        <BasicTable
          v-if="deptsData.depts"
          @register="registerInDeptTable"
          :can-resize="true"
          :bordered="true"
          :striped="true"
          :loading="false"
          :data-source="deptsData.depts"
        >
          <!-- <template #toolbar>
            <a-button @click="exportInDeptToExcel"> 导出Excel </a-button>
          </template> -->
        </BasicTable>
      </div>
    </div>

    <!-- 饼图显示数据 -->
    <div style="width: 100%; margin-top: 8px">
      <div ref="chartRef" :style="{ height, width }"></div>
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, onBeforeMount, onMounted, onUnmounted, reactive, ref, Ref } from 'vue';

  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable } from '/@/components/Table';

  import {
    queryConditionFormSchema,
    queryTableByInUserColumns,
    queryTableByInDeptColumns,
    inUserArrHeader,
  } from './statistics.data';
  import { mergeCellsByInUser, mergeCellsByInDept, computeMergeRow } from './mergeCells';

  import { ArticleStatisticsConditionDto } from '/@/api/cms/model/statisticsModel';

  import {
    queryStatisticsByInUserAndDept,
    queryStatisticsByInUserAndDeptNotMerged,
  } from '/@/api/cms/statistics';

  import moment from 'moment';

  import { useECharts } from '/@/hooks/web/useECharts';

  import * as XLSX from 'xlsx';

  export default defineComponent({
    name: 'StatisticsManagement',
    components: { BasicForm, BasicTable },
    props: {
      // 饼图显示部分的宽高
      width: {
        type: String as PropType<string>,
        default: '98.7%',
      },
      height: {
        type: String as PropType<string>,
        default: 'calc(100vh - 330px)',
      },
    },
    setup() {
      //按发布人统计文章结果数据
      const authorsData = reactive({
        authors: [],
      });

      //按发布部门统计文章结果数据
      const deptsData = reactive({
        depts: [],
      });

      //按发布人统计文章图表展示结果数据
      const topAuthorsData = reactive({
        authors: [],
      });

      //按发布部门统计文章图表展示结果数据
      const pieDeptsData = reactive({
        depts: [],
      });

      //需要导出的数据
      const exportAuthorsData = reactive({
        authors: [],
      });

      const chartRef = ref<HTMLDivElement | null>(null);
      const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

      /**
       * 按发布人统计数据导出excel文件
       */
      //需要导出的数组数据
      let arrAuthorData = [];
      function exportInUserToExcel() {
        const filename = '文章统计.xlsx'; //导出文件名
        const worksheet_name = 'Sheet1'; // Excel第一个sheet的名称
        const workbook = XLSX.utils.book_new(); //创建一个新的workbook
        const worksheet = XLSX.utils.aoa_to_sheet(arrAuthorData);

        console.log('arrAuthorData', arrAuthorData);

        //合并单元格
        //找出需要合并的单元格位置数组
        let mergesArr = computeMergeRow(authorsData.authors); //['A1:A2','B1:B2',...]
        console.log('mergesArr', mergesArr);
        let arr = [];
        mergesArr.forEach((merge) => {
          // console.log('111', XLSX.utils.decode_range(merge)); //输出格式为：{e: {c: 1, r: 1},s: {c: 0, r: 0}}
          arr.push(XLSX.utils.decode_range(merge));
        });
        worksheet['!merges'] = arr;

        //列宽设置
        worksheet['!cols'] = [
          { width: 10 },
          { width: 10 },
          { width: 60 },
          { width: 20 },
          { width: 20 },
          { width: 20 },
        ];

        //保存数据信息并下载文件
        XLSX.utils.book_append_sheet(workbook, worksheet, worksheet_name); //将数据添加到工作簿
        XLSX.writeFile(workbook, filename); //下载excel文件
      }

      /**
       * 表单的查询条件
       */
      let time = new Date();
      let monthNum = moment().month();
      let queryConditionDto: ArticleStatisticsConditionDto = {
        begintm: moment(time).month(monthNum).date(1).startOf('month').format('YYYY-MM-DD'), //默认当月第一天
        endtm: moment(time).month(monthNum).date(1).endOf('month').format('YYYY-MM-DD'), //默认当月最后一天
        ids: [],
        author: '',
        dept: '',
      };

      onBeforeMount(() => {
        console.log('DOM即将挂载');
        queryArticleStatistics();
      });
      onMounted(() => {});
      onUnmounted(() => {
        console.log('销毁完毕');
      });

      /**
       * 查询表单
       */
      const [registerForm] = useForm({
        labelWidth: 80,
        schemas: queryConditionFormSchema,
      });

      /**
       * 按发布人统计文章table
       */
      const [registerInUserTable] = useTable({
        title: '按发布人统计文章（按发布人名称先后顺序排列）',
        columns: queryTableByInUserColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        striped: false, //斑马纹
        showIndexColumn: false,
        pagination: false,
        size: 'small',
        scroll: { y: 450 },
      });

      /**
       * 按发布部门统计文章table
       */
      const [registerInDeptTable] = useTable({
        title: '按发布部门统计文章（按发布部门名称先后顺序排列）',
        columns: queryTableByInDeptColumns, //表头数据
        showTableSetting: false, //是否显示表格设置
        bordered: true,
        striped: false, //斑马纹
        showIndexColumn: false,
        pagination: false,
        size: 'small',
        scroll: { y: 450 },
      });

      /**
       * 查询按发布人和发布名称统计文章
       */
      async function queryArticleStatistics() {
        if (authorsData.authors.length > 0) {
          authorsData.authors = [];
        }
        if (deptsData.depts.length > 0) {
          deptsData.depts = [];
        }
        if (topAuthorsData.authors.length > 0) {
          topAuthorsData.authors = [];
        }
        if (pieDeptsData.depts.length > 0) {
          pieDeptsData.depts = [];
        }
        if (exportAuthorsData.authors.length > 0) {
          exportAuthorsData.authors = [];
        }

        //查询按部门统计图表显示数据
        queryStatisticsByInUserAndDept(queryConditionDto)
          .then((res) => {
            // console.log('-=-=-=-=-=-', res);
            res.depts.forEach((val) => {
              let dept = {
                name: val.name,
                value: val.count,
              };
              pieDeptsData.depts.push(dept);
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
          });

        //查询文章统计表格显示数据
        queryStatisticsByInUserAndDeptNotMerged(queryConditionDto)
          .then((res) => {
            console.log('res', res);
            //处理请求结果
            if (res.authors != null) {
              authorsData.authors = res.authors;
              //合并单元格处理
              mergeCellsByInUser(authorsData.authors);
            }
            if (res.depts != null) {
              deptsData.depts = res.depts;
              //合并单元格处理
              mergeCellsByInDept(deptsData.depts);
            }
            if (res.topAuthors != null) {
              res.topAuthors.forEach((val) => {
                let author = {
                  name: val.name,
                  value: val.count,
                };
                topAuthorsData.authors.push(author);
              });
            }

            //处理导出excel的数据，转为数组格式
            exportAuthorsData.authors.push(inUserArrHeader);
            authorsData.authors.forEach((author) => {
              let value = {
                inuser: author.inuser,
                inUserCount: author.inUserCount,
                title: author.title,
                intm: moment(author.intm).format('YYYY-MM-DD'),
                indept: author.indept,
                author: author.author,
              };
              exportAuthorsData.authors.push(value);
            });
            arrAuthorData = exportAuthorsData.authors.map((item) => {
              return Object.keys(item).map((key) => item[key]);
            });

            //绘制饼图
            setOptions({
              backgroundColor: '#fff',
              title: [
                {
                  text: '发布人统计图（显示前5名）',
                  left: '1%',
                  top: '1%',
                  textStyle: {
                    // color: '#fff',
                    color: '#000',
                    fontSize: 14,
                  },
                },
                {
                  text: '发文部门统计图',
                  left: '51%',
                  top: '1%',
                  textStyle: {
                    // color: '#fff',
                    color: '#000',
                    fontSize: 14,
                  },
                },
              ],
              tooltip: {
                formatter: '{b}:{c} ({d}%)',
              },
              series: [
                {
                  name: '按发布人统计文章',
                  type: 'pie',
                  radius: '50%',
                  center: ['25%', '45%'],
                  data: topAuthorsData.authors,
                  color: [
                    '#5470c6',
                    '#91cc75',
                    '#fac858',
                    '#ee6666',
                    '#73c0de',
                    '#3ba272',
                    '#fc8452',
                    '#9a60b4',
                    '#ea7ccc',
                  ],
                  labelLine: { show: true },
                  label: {
                    show: true,
                    formatter: '{b}:{c} ({d}%)',
                    // color: '#B1B9D3',
                  },
                },
                {
                  name: '按发布部门统计文章',
                  type: 'pie',
                  radius: '50%',
                  center: ['75%', '45%'],
                  labelLine: { show: true },
                  data: pieDeptsData.depts,
                  color: [
                    '#5470c6',
                    '#91cc75',
                    '#fac858',
                    '#ee6666',
                    '#73c0de',
                    '#3ba272',
                    '#fc8452',
                    '#9a60b4',
                    '#ea7ccc',
                  ],
                  label: {
                    show: true,
                    formatter: '{b}:{c} ({d}%)',
                    // color: '#B1B9D3',
                  },
                },
              ],
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
          });
      }

      /**
       * 表单提交按钮事件
       */
      function handleSubmit(values: any) {
        console.log(values);
        let date = values.beginEndtm;
        // console.log('date', date);
        let beginDate;
        let endDate;
        for (let i = 0; i < date.length; i++) {
          beginDate = date[0];
          endDate = date[1];
        }
        queryConditionDto.begintm = beginDate;
        queryConditionDto.endtm = endDate;
        queryConditionDto.ids = values.ids;
        // 调用查询函数
        queryArticleStatistics();
      }

      return {
        registerForm,
        registerInUserTable,
        registerInDeptTable,

        handleSubmit,
        queryArticleStatistics,

        authorsData,
        deptsData,
        topAuthorsData,

        chartRef,

        exportInUserToExcel,
      };
    },
  });
</script>
